<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Aboot\ProductNumber;
use App\Model\Admin\Product;
use App\Model\Admin\ProductAttr;
use Illuminate\Http\Request;

class ProductNumberController extends Controller
{
    public function number($id)
    {
        /**
        * 取出多个属性id，嵌套 有多个属性的二维数组
        **/
        $attr_g = ProductAttr::select('attr_id')->where('product_id', '=', $id)->groupBy('attr_id')->having(\DB::raw("count(*)"), '>', 1)->get();
        $attr_s = ProductAttr::leftJoin('product_attributes', 'product_attrs.attr_id', 'product_attributes.id')->where('product_attrs.product_id', $id)->select('product_attrs.*', 'product_attributes.attr_name')->whereIn('product_attrs.attr_id', $attr_g)->get();
        // dd($attr_s);
        ##################属性相同的放在一起；
        $attrs = array();
        foreach ($attr_s as $k=>$v) {
            $attrs[$v['attr_id']][] = $v;
        }
    	$nums = ProductNumber::where('product_id',$id)->get();

        return view('admin.product.number.index', compact('attrs','nums'))
             ->with('product', Product::find($id));
    }


    /**
    * $request->product_attr_id 属性id
    * $request->product_number  库存
    * return @true ? false
    */	
    public function store(Request $request, $id)
    {	

    		// dd($request->input());
    		$pra = $request->input('product_attr_id');
    		$prn = $request->input('product_number');
    		//计算数组比例

    		$rate = count($pra) / count($prn);
    		$_i = 0 ; //从第几个开始
    		//循环每个库存量插入表
    		ProductNumber::where('product_id',$id)->delete();
    		
    		foreach($prn as $k=>$v)
    		{
    			$_arr = array();
    			for ($i = 0; $i < $rate ; $i++) 
    			{
    				$_arr[] = $pra[$_i];
    				$_i++;
    			}
    			//升序排序
    			sort($_arr);
    			//以逗号分割数组
    			$_arr = implode(',', $_arr);
    			ProductNumber::create([
    					       'product_id'=> $id,
    					       'product_number'=> $v,
    					       'product_attr_id'=>$_arr
    			]);
    		}
    		return back();

    }
 


}
